<?php

class CL_MySQL {

    private static $instance = NULL;
    private $config;
    private $connection;

    private function CL_MySQL() {
        $this->config = CL_Config::get_instance();
        $this->connection = NULL;
    }

    /**
     * @return CL_MySQL
     */
    public static function get_instance() {
        if (self::$instance === NULL) {
            self::$instance = new CL_MySQL();
        }
        return self::$instance;
    }

    public function connect() {

        if ($this->connection == NULL) {
            $server = $this->config->get_item('database', 'server');
            $username = $this->config->get_item('database', 'username');
            $password = $this->config->get_item('database', 'password');
            $database = $this->config->get_item('database', 'database');
            $this->connection = mysql_connect($server, $username, $password);
            mysql_set_charset('utf8');
            mysql_select_db($database);
        }
    }

    public function close() {
        if ($this->connection !== NULL) {
            mysql_close($this->connection);
            $this->connection = NULL;
        }
    }

    public function  __destruct() {
        $this->close();
    }

    public function query($q) {

        if ($this->connection === NULL) {
            $this->connect();
        }

        $result = mysql_query($q);

        if (!$result) {
            show_error(mysql_error(), 'MySQL Error');
        }
        
        return $result;
    }

    public function num_rows($r) {
        return mysql_num_rows($r);
    }

    public function affected_rows() {
        return mysql_affected_rows();
    }

    public function fetch_object($r) {
        return mysql_fetch_object($r);
    }

    public function insert_id() {
        return mysql_insert_id();
    }

    public function begin() {
        mysql_query('BEGIN');
    }

    public function rollback() {
        mysql_query('ROLLBACK');
    }

    public function commit() {
        mysql_query('COMMIT');
    }
}